package com.example.newstest.pic;


import android.databinding.DataBindingUtil;
import android.databinding.ObservableInt;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.util.Pair;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.example.newstest.BR;

import com.example.newstest.callback.NewsService;
import com.example.newstest.databinding.FragmentPicBinding;
import com.example.newstest.pic.bean.PicItem2Entity;
import com.example.newstest.pic.bean.PicItemEntity;
import com.example.newstest.until.BaseApplication;
import com.example.newstest.until.CommentRecyclerAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.example.newstest.R;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import in.srain.cube.views.ptr.PtrUIHandler;
import in.srain.cube.views.ptr.indicator.PtrIndicator;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * A simple {@link Fragment} subclass.
 */
public class PicFragment extends Fragment implements Callback<List<PicItemEntity>>, PtrHandler {
    private FragmentPicBinding binding;
    private CommentRecyclerAdapter<Object> adapter;
    private NewsService service;
    private String  time = System.currentTimeMillis()+"";
    private int isRefresh = -1;
    private boolean isLoading = false;
    private String id ;
    public PicFragment() {

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return DataBindingUtil.inflate(inflater, R.layout.fragment_pic, container, false).getRoot();
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        binding = DataBindingUtil.getBinding(view);
        HashMap<Class<?>, Pair<Integer, Integer>> map = new HashMap<>();
        map.put(PicItemEntity.class, Pair.create(R.layout.pic_item1, BR.picItem1));
        map.put(PicItem2Entity.class, Pair.create(R.layout.pic_item2, BR.picItem2));
        adapter = new CommentRecyclerAdapter<>(getContext(), new ArrayList<>(), map);
        binding.recycler.setAdapter(adapter);
       service = ((BaseApplication) getActivity().getApplication()).getService();
        service.getPicItemList(time,"0").enqueue(this);
        aboutRefresh();
        aboutNextPage();
    }
    private void aboutNextPage() {
        binding.recycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                View item = recyclerView.getChildAt(recyclerView.getChildCount() - 1);
                int position = recyclerView.getChildAdapterPosition(item);
                if (!isLoading && position > adapter.getItemCount() - 5) {
                    service.getPicItemList(time,id).enqueue(PicFragment.this);
                    isLoading = true;
                }
            }
        });
    }
    @Override
    public void onResponse(Call<List<PicItemEntity>> call, Response<List<PicItemEntity>> response) {
        if (isRefresh == -1) {
            adapter.clear();
            for (int i = 0; i < response.body().size(); i++) {
                if (i == 0 | i % 4 == 0) {
                    adapter.add(response.body().get(i));
                } else {
                    PicItemEntity item = response.body().get(i);
                    PicItem2Entity item2 = new PicItem2Entity(item.getImgcount(), item.getId(), item.getTitle(), item.getPostdate(), item.getEditor(), item.getReviewcount(), item.getIcon(), item.getIspass(), item.getIsdel(), item.getSmallimgsrc(), item.getBigimgsrc());
                    List<String> list = new ArrayList<>();
                    String[] split = item.getSmallimgsrc().split("url=");
                    for (int j = 1; j < split.length; j++) {
                        if (split[j].endsWith("&")) {
                            String[] split1 = split[j].split("\\|");
                            list.add(split1[0]);
                        } else {
                            list.add(split[j]);
                        }
                    }
                    item2.setSmallUrlList(list);
                    adapter.add(item2);
                }
            }
            isRefresh = -2;
            binding.ptr.refreshComplete();
        } else {
            for (int i = 0; i < response.body().size(); i++) {
                if (i == 0 | i % 4 == 0) {
                    adapter.add(response.body().get(i));
                } else {
                    PicItemEntity item = response.body().get(i);
                    PicItem2Entity item2 = new PicItem2Entity(item.getImgcount(), item.getId(), item.getTitle(), item.getPostdate(), item.getEditor(), item.getReviewcount(), item.getIcon(), item.getIspass(), item.getIsdel(), item.getSmallimgsrc(), item.getBigimgsrc());
                    List<String> list = new ArrayList<>();
                    String[] split = item.getSmallimgsrc().split("url=");
                    for (int j = 1; j < split.length; j++) {
                        if (split[j].endsWith("&")) {
                            String[] split1 = split[j].split("\\|");
                            list.add(split1[0]);
                        } else {
                            list.add(split[j]);
                        }
                    }
                    item2.setSmallUrlList(list);
                    adapter.add(item2);
                }
            }
        }
        isLoading = false;
        id = response.body().get(response.body().size() - 1).getId() + "";
    }

    private void aboutRefresh() {
        binding.ptr.setPtrHandler(this);
        final ImageView imageView = new ImageView(getContext());
        final TextView textView = new TextView(getContext());
        LinearLayout linearLayout = new LinearLayout(getContext());
        linearLayout.setGravity(Gravity.CENTER_HORIZONTAL);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        linearLayout.addView(textView);
        linearLayout.addView(imageView);
        imageView.setImageResource(R.mipmap.arrow_down);
        textView.setText("开始刷新,请稍后....");
        textView.setGravity(Gravity.CENTER);
        binding.ptr.setHeaderView(linearLayout);
        binding.ptr.addPtrUIHandler(new PtrUIHandler() {
            @Override
            public void onUIReset(PtrFrameLayout frame) {
                ViewCompat.setScaleY(imageView,1);
                ViewCompat.setScaleX(imageView,1);
                ViewCompat.setRotation(imageView,0);
            }

            @Override
            public void onUIRefreshPrepare(PtrFrameLayout frame) {

            }

            @Override
            public void onUIRefreshBegin(PtrFrameLayout frame) {
                textView.setText("正在刷新,请稍后...");
                ViewCompat.animate(imageView)
                        .rotation(180)
                        .setDuration(500)
                        .start();
            }

            @Override
            public void onUIRefreshComplete(PtrFrameLayout frame) {

            }

            @Override
            public void onUIPositionChange(PtrFrameLayout frame, boolean isUnderTouch, byte status, PtrIndicator ptrIndicator) {
                float percent = ptrIndicator.getCurrentPercent();
                percent =  Math.min(percent, 1);
                ViewCompat.setScaleX(imageView, percent);
                ViewCompat.setScaleY(imageView, percent);
            }
        });
    }
    @Override
    public void onFailure(Call<List<PicItemEntity>> call, Throwable t) {
        t.getMessage();
        Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_LONG).show();
    }

    @Override
    public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
        return PtrDefaultHandler.checkContentCanBePulledDown(frame,content,header);
    }

    @Override
    public void onRefreshBegin(PtrFrameLayout frame) {
        isRefresh=-1;
        service.getPicItemList(time,"0").enqueue(this);
    }
}
